package com.zhou.utils;

import com.zhou.configure.PushConfigure;
import com.zhou.dto.IdentityInfo;
import com.zhou.dto.ResponseMessage;
import com.zhou.enums.WxMessageType;
import lombok.extern.slf4j.Slf4j;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Map;

/**
 * @author lcz
 * @desc 操作工具类
 * @mail lcz_0130@163.com
 * @date 2023/12/28
 */

@Slf4j
public class WxOpUtils {

    private WxOpUtils() {
    }

    public static void returnMessages(HttpServletResponse response, ResponseMessage responseMessage) throws IOException {
        try (PrintWriter printWriter = response.getWriter()) {
            // 转化成微信可接收的xml信息返回
            String transformedMessage = transformMessage(responseMessage);
            log.info("回复消息 : {}", responseMessage.getContent());
            printWriter.println(transformedMessage);
        }
    }

    /**
     * 将信息转换成xml返回
     *
     * @param textMessage 存储回复信息的对象
     * @return 微信指定接受的回复信息格式（xml）
     */
    public static String transformMessage(ResponseMessage textMessage) {
        String responseMessage = "<xml>\n" +
                "  <ToUserName><![CDATA[" + textMessage.getToUserName() + "]]></ToUserName>\n" +
                "  <FromUserName><![CDATA[" + textMessage.getFromUserName() + "]]></FromUserName>\n" +
                "  <CreateTime>" + System.currentTimeMillis() + "</CreateTime>\n" +
                "  <MsgType><![CDATA[" + textMessage.getMsgType() + "]]></MsgType>\n";
        if (textMessage.getMsgType().equals(WxMessageType.TEXT.getType())) {
            responseMessage = responseMessage + "  <Content><![CDATA[" + textMessage.getContent() + "]]></Content>\n";
        } else if (textMessage.getMsgType().equals(WxMessageType.TRANSFER_CUSTOMER_SERVICE.getType())) {
            responseMessage = responseMessage +
                    "  <TransInfo>\n" +
                    "    <KfAccount><![CDATA[" + "WxConstants.CUSTOMER_SERVICE" + "]]></KfAccount>\n" +
                    "  </TransInfo>\n";
        }
        return responseMessage + "</xml>";
    }


}
